from django.shortcuts import render, redirect
from django.contrib import messages
from django.core.mail import EmailMessage
from django.utils.html import strip_tags
from app.forms import ContactForm
from django.utils.translation import gettext_lazy as _
from settings.utils import all_settings, get_setting


def home(request):
    context = {
        'settings': all_settings(),
    }
    return render(request, 'home.html', context)


def contact(req):

    if req.method == 'POST':
        form = ContactForm(req.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            subject = strip_tags(form.cleaned_data['subject'])
            message = strip_tags(form.cleaned_data['message'])

            # Send a message.
            try:
                subject = f"{subject}, ({email})!"
                from_email = f"{get_setting('SITE_NAME')} <{get_setting('SMTP_USER')}>"
                to_emails = [get_setting('SMTP_USER')]
                mail = EmailMessage(subject, message, from_email,
                                    to_emails, reply_to=[email])
                mail.send()
                messages.success(req, _('Sent Successfully :D'))
            except Exception as e:
                print(e)
                messages.warning(req, _('Something went wrong!'))

        return redirect('contact')
    else:
        form = ContactForm()

    context = {
        'title': _('Contact Us'),
        'form': form,
        'settings': all_settings(),
    }

    return render(req, 'contact.html', context)


def Page404(request, exception=None):
    """Custom 404 page."""
    return render(request, "errors/404.html")

def Page403(request, exception=None):
    """Custom 403 page."""
    return render(request, "errors/403.html")

def Page400(request, exception=None):
    """Custom 400 page."""
    return render(request, "errors/400.html")

def Page500(request, exception=None):
    """Custom 500 page."""
    return render(request, "errors/500.html")

